C++ provides means for exception (or error) handling. You use the 'try', 'catch', and 'throw' keywords for this purpose. When programming, you tell the compiler to 'try' a section of code. If an error occurs in the section (or in any nested methods/functions in the section), you 'throw' an exception. The exception is then handled like a hot potato and is passed up the ladder until it is caught. If an exception is not caught, the program terminates. Here's the basic syntax:
// exceptions.cp
#include <iostream.h>
void doFunction( float x );
main()
{
float val = 5.0;
try
{
doFunction( val );
}
catch( const char *s )
{
cout << "string exception caught" << endl;
cout << s << endl;
}
catch(...)
{
// catch all other exceptions here
}
return 0;
}
void doFunction( float x )
{
float limit = 3.14159;
if( x > limit )
throw "value exceeds limit";
}
// end exceptions.cp
In most C++ applications, you 'throw' an exception class object rather than a string or error code. An example of this is shown below: